﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting;
using System.Windows.Forms;

namespace RoketProtocol
{
    class Manager
    {
        /// <summary>
        /// Attempts to connect to the server IPC channel (relies on RoketPack already
        /// running on the local computer).  If it successfully connects, it sends a 
        /// request for RoketPack to load the URL that was specified on the command line.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        internal bool PerformInstallation(string name)
        {
            try
            {
                // The server appears to be already running.  Connect to
                // the channel as a client and send instructions back
                // to the server.
                IpcClientChannel client = new IpcClientChannel();
                ChannelServices.RegisterChannel(client, true);

                API.InterProcess i = (API.InterProcess)Activator.GetObject(
                    typeof(API.InterProcess),
                    "ipc://" + name + "/InterProcessManager");

                if (i == null)
                {
                    string msg = "Unable to communicate with or initialize the RoketPack software service.  The requested software will not be installed.";
                    string caption = "Software Installation";
                    MessageBox.Show(msg, caption, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return false;
                }

                if (Environment.GetCommandLineArgs().Length > 1)
                    i.AuthorizedCallURL(Environment.GetCommandLineArgs()[1]);

                return true;
            }
            catch (RemotingException)
            {
                string msg = "Unable to communicate with or initialize the RoketPack software service.  The requested software will not be installed.";
                string caption = "Software Installation";
                MessageBox.Show(msg, caption, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }
        }
    }
}
